import { useState, useCallback } from 'react';
import { useMultiChainWallet } from '@/contexts/MultiChainWalletContext';
import { useMultiChainBSCOperations } from '@/hooks/useMultiChainBSC';
import { MultiChainWalletStatus } from './MultiChainWalletStatus';
import { toast } from 'react-hot-toast';
import Image from 'next/image';
import type { CreateBSCTokenParams, BSCToken } from '@/types/bsc';

interface CreateBSCTokenFormProps {
  onSuccess?: (token: BSCToken) => void;
  onClose?: () => void;
}

export function CreateBSCTokenForm({ onSuccess, onClose }: CreateBSCTokenFormProps) {
  const { connected, chain, address } = useMultiChainWallet();
  const { createToken, isLoading } = useMultiChainBSCOperations();
  
  const [formData, setFormData] = useState({
    name: '',
    symbol: '',
    description: '',
    targetAmount: '10', // BNB
    website: '',
    twitter: '',
    telegram: ''
  });
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string>('');

  const handleImageChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        toast.error('图片大小不能超过5MB');
        return;
      }
      
      setImageFile(file);
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!connected || chain !== 'bsc') {
      toast.error('请先连接BSC钱包');
      return;
    }

    if (!formData.name || !formData.symbol) {
      toast.error('请填写代币名称和符号');
      return;
    }

    if (!imageFile) {
      toast.error('请上传代币图片');
      return;
    }

    try {
      const tokenParams: CreateBSCTokenParams = {
        name: formData.name,
        symbol: formData.symbol,
        description: formData.description,
        targetAmount: formData.targetAmount,
        website: formData.website,
        twitter: formData.twitter,
        telegram: formData.telegram,
        imageFile: imageFile,
      };

      const result = await createToken(tokenParams);
      toast.success('BSC代币创建成功！');
      onSuccess?.(result);
    } catch (error) {
      console.error('创建BSC代币失败:', error);
      toast.error(error instanceof Error ? error.message : '创建失败');
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  return (
    <div className="bg-gray-900 border border-gray-700 rounded-lg p-6 max-w-2xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-pixel text-white">创建BSC代币</h2>
        {onClose && (
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white text-xl"
          >
            ✕
          </button>
        )}
      </div>

      {/* 钱包连接状态 */}
      <div className="mb-6">
        <div className="flex items-center gap-4 p-4 bg-gray-800 rounded-lg border border-gray-700">
          <div className="flex-1">
            {connected && chain === 'bsc' ? (
              <div className="flex items-center gap-2 text-green-400">
                <span className="w-2 h-2 bg-green-400 rounded-full"></span>
                <span>BSC钱包已连接</span>
                <span className="text-gray-300 text-sm">({address?.slice(0, 6)}...{address?.slice(-4)})</span>
              </div>
            ) : (
              <div className="flex items-center gap-2 text-yellow-400">
                <span className="w-2 h-2 bg-yellow-400 rounded-full"></span>
                <span>请连接BSC钱包以创建代币</span>
              </div>
            )}
          </div>
          <MultiChainWalletStatus />
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 基本信息 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              代币名称 *
            </label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
              placeholder="例如: My Token"
              required
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              代币符号 *
            </label>
            <input
              type="text"
              name="symbol"
              value={formData.symbol}
              onChange={handleInputChange}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
              placeholder="例如: MTK"
              required
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            目标筹集金额 (BNB)
          </label>
          <input
            type="number"
            name="targetAmount"
            value={formData.targetAmount}
            onChange={handleInputChange}
            className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
            placeholder="10"
            min="0.1"
            step="0.1"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            代币描述
          </label>
          <textarea
            name="description"
            value={formData.description}
            onChange={handleInputChange}
            rows={3}
            className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
            placeholder="描述你的代币..."
          />
        </div>

        {/* 图片上传 */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            代币图片 *
          </label>
          <div className="flex items-center gap-4">
            <input
              type="file"
              accept="image/*"
              onChange={handleImageChange}
              className="hidden"
              id="tokenImage"
            />
            <label
              htmlFor="tokenImage"
              className="cursor-pointer bg-gray-800 border border-gray-600 rounded-lg px-4 py-2 text-white hover:bg-gray-700"
            >
              选择图片
            </label>
            {imagePreview && (
              <Image
                src={imagePreview}
                alt="代币图片预览"
                width={64}
                height={64}
                className="rounded-lg object-cover"
              />
            )}
          </div>
        </div>

        {/* 社交链接 */}
        <div className="space-y-4">
          <h3 className="text-lg font-medium text-white">社交链接 (可选)</h3>
          
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              网站
            </label>
            <input
              type="url"
              name="website"
              value={formData.website}
              onChange={handleInputChange}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
              placeholder="https://example.com"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              Twitter
            </label>
            <input
              type="url"
              name="twitter"
              value={formData.twitter}
              onChange={handleInputChange}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
              placeholder="https://twitter.com/username"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              Telegram
            </label>
            <input
              type="url"
              name="telegram"
              value={formData.telegram}
              onChange={handleInputChange}
              className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:border-purple-500"
              placeholder="https://t.me/username"
            />
          </div>
        </div>

        {/* 提交按钮 */}
        <div className="flex gap-4">
          <button
            type="submit"
            disabled={isLoading || !connected || chain !== 'bsc'}
            className={`flex-1 py-3 px-6 rounded-lg font-medium transition-colors ${
              isLoading || !connected || chain !== 'bsc'
                ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                : 'bg-purple-600 hover:bg-purple-700 text-white'
            }`}
          >
            {isLoading ? '创建中...' : '创建BSC代币'}
          </button>
          
          {onClose && (
            <button
              type="button"
              onClick={onClose}
              className="px-6 py-3 border border-gray-600 text-gray-300 rounded-lg hover:bg-gray-800"
            >
              取消
            </button>
          )}
        </div>
      </form>
    </div>
  );
}
